/**
 * 登录界面封装
 * @author hongwei 2018-09-19
 */
(function (window) {
    'use strict';
    var login = function (params) {
        $.extend(this.params, params);
        this._init();
    };

    //var jpush = api.require('ajpush');

    login.prototype = {
        //参数
        params : {
            
        }

        //初始化操作
        ,_init : function () {
            var that = this;
            if(typeof(api) === 'undefined'){
                console.log('该插件只能在apicloud下运行');
            } else {
                that.jpush = api.require('ajpush');
                that.headerInit();               //step1:头部沉浸式
                that.loginSubmit(that.jpush);    //step3:登录提交，包含step5
                that.forget_password();          //step4:忘记密码
                that.myFunctionSelect();         //step11:点击公司根据手机号进行加载公司列表-采用jquery
                that.exitApp();                  //step10:双击退出 监听
            }
        }
        
        //step1:头部沉浸式
        ,headerInit : function () {
            //头部操作
            var header = $api.byId('header');
            $api.fixStatusBar(header);
        }

        //step3:登录提交
        ,loginSubmit : function (jpush) {
            var that = this;
            $('#login').click(function () {
                var company_name = $.trim($("#company-name").text());
                var user_name = $.trim($('#user-name').val());
                var password = $.trim($('#password').val());
                if (!company_name || !password || !user_name) {
                    $toast("请补充必填信息!");
                    return false;
                }
                var param = {};
                param.url = Config.user.userLogin;
                param.data = {
                    'company_name': company_name,
                    'user_name': user_name,
                    'password': password,
                    'device_type': api.systemType
                };
                ajax(param, function(ret) {
                    if (ret.code === 1) {
                        //step1:存储信息
                        $api.setStorage('token', ret.data.token);
                        $api.setStorage('user_id', ret.data.user.user_id);
                        $api.setStorage('company_id', ret.data.user.company_id);
                        $toast(ret.msg);
                        setTimeout(function() {
                            //step2:绑定极光
                            that.bindAliasAndTagsFunction($api.getStorage('user_id'), 'develop,dist',jpush);
                            //step3:获取唯一ID
                            var registrationID = that.getId(jpush);
                            $api.setStorage('jpush_id', registrationID);
                            //step4:更新用户表相关极光iD
                            that.existAndModifyPushId();
                            //step5:打开
                            api.openWin({
                                name: 'main',
                                url: '../main.html',
                                slidBackEnabled: false
                            });
                        }, 1500);
                    } else {
                        $toast(ret.msg);
                    }
                });
            });
        }

        //step4:忘记密码
        ,forget_password : function () {
            $('#forget_password').click(function () {
                api.openWin({
                    name: 'forget_password_win',
                    url: './forget_password_win.html',
                    slidBackEnabled: false
                });
            });
        }

        /**
         * step5:更新用户的推送ID
         * @author hongwei 2018-07-24
         */
        ,existAndModifyPushId : function () {
            var that = this;

            var param = {};
            param.url = Config.user.userDetail;
            param.data = {};
            ajax(param, function(ret){
                if (ret.code === 1) {
                    //更新push_id
                    that.editUserPushId(ret.data.push_id);
                }
            })
        }

        /**
         * step6:更新用户的极光推送ID
         * @author hongwei 2018-07-24
         */
        ,editUserPushId :function (pushId) {
            var param = {};
            param.url = Config.user.userEdit;
            param.data = {
                'push_id' : pushId
            };
            ajax(param, function(ret){
                if (ret.code === 1) {
                    console.log('更新用户极光推送的ID成功！');
                }
            })
        }

        /**
         * step8.获取getRegistrationId
         */
        ,getId :function (jpush){
            jpush.getRegistrationId(function(ret, err){
                //console.log(JSON.stringify(ret));
                //todo
            });
        }

        /**
         * step9.进行绑定bindAliasAndTags 及存储 registrationID
         * @author hongwei
         */
        ,bindAliasAndTagsFunction : function (alias, tags, jpush){
            if (alias === 'test') {
                var deviceId = api.deviceId;
                alias   = deviceId.replace(/-/g,'');
                tags    = 'develop,dist'; //tag值
            }
            if(!alias && !tags){
                alert('别名和标签至少传一个');
                return;
            }
            if(!alias){
                alias = '';
            }
            if(tags){
                tags = tags.split(',');
            }
            jpush.bindAliasAndTags({
                alias:alias,
                tags:tags
            }, function(ret, err){
                //alert('处理结果：\n' + JSON.stringify(ret));
                var statusCode = ret.statusCode;
                if(statusCode === 0){
                        //todo
                }
            });
        }

        /**
         * step10:双击退出 监听
         * @author tong
         */
        ,exitApp :function () {
            var that = this;
            api.addEventListener({
                name: 'keyback'
            }, function(ret, err) {
                $toast('再按一次退出' + api.appName, 2000);
                api.addEventListener({
                    name: 'keyback'
                }, function(ret, err) {
                    api.closeWidget({
                        silent: true
                    });
                });
                //2秒后重新调用当前函数
                setTimeout(function() {
                    that.exitApp();
                }, 2000)
            });
        }

        //step11:点击公司根据手机号进行加载公司列表-采用jquery
        ,myFunctionSelect : function () {
            var that = this;

            var picker1El = document.getElementById('picker1');  //审核人 选择器
            //添加触发
            picker1El.addEventListener('click', function() {
                var x = document.getElementById("user-name").value;

                if (x.length === 11) {

                    $.post(Config.user.getCompanyList, {phone: x}, function (ret) {
                        console.log(JSON.stringify(ret));
                        if (ret.code === 1) {
                            //picker
                            var dataTemp = ret.data;
                            //var dataTemp = [{"company_id":1,"company_name":"山西创泰网络科技"},{"company_id":31,"company_name":"上海测试公司一"}];
                            var data1 = [];
                            that.createList(dataTemp, data1);

                            var picker1 = new Picker({
                                data: [data1],
                                //selectedIndex: [0],
                                title: '请选择公司'
                            });
                            //选择后调用
                            picker1.on('picker.select', function(selectedVal, selectedIndex) {
                                $('#company-name').empty().text(data1[selectedIndex[0]].text);
                            });

                            if (data1.length > 0) {
                                picker1.show(function() {
                                    picker1.refill([data1]);
                                });
                            } else {
                                toast.custom({
                                    title: "该手机号下不存在相应的公司",
                                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                                    duration: 2000
                                });
                            }

                        } else {
                            $toast(ret.msg);
                        }
                    });
                }
            });
        }

        //step12:点击公司根据手机号进行加载公司列表-采用ajax
        ,myFunctionSelect2 : function () {
            var that = this;

            var picker1El = document.getElementById('picker1');  //审核人 选择器
            //添加触发
            picker1El.addEventListener('click', function() {
                var x = document.getElementById("user-name").value;

                if (x.length === 11) {
                    var param = {};
                    param.url = Config.user.getCompanyList;
                    param.data = {phone: x};
                    that.ajaxNoHeader(param, function (ret) {
                        console.log(JSON.stringify(ret));
                        if (ret.code === 1) {
                            //picker
                            var dataTemp = ret.data;
                            //var dataTemp = [{"company_id":1,"company_name":"山西创泰网络科技"},{"company_id":31,"company_name":"上海测试公司一"}];
                            var data1 = [];
                            that.createList(dataTemp, data1);

                            var picker1 = new Picker({
                                data: [data1],
                                //selectedIndex: [0],
                                title: '请选择公司'
                            });
                            //选择后调用
                            picker1.on('picker.select', function(selectedVal, selectedIndex) {
                                $('#company-name').empty().text(data1[selectedIndex[0]].text);
                            });

                            if (data1.length > 0) {
                                picker1.show(function() {
                                    picker1.refill([data1]);
                                });
                            } else {
                                toast.custom({
                                    title: "该手机号下不存在相应的公司",
                                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                                    duration: 2000
                                });
                            }

                        } else {
                            $toast(ret.msg);
                        }
                    });
                }
            });
        }

        ,createList :function (obj, list){
            obj.forEach(function(item, index, arr){
                var temp = [];
                temp.text = item.company_name;
                temp.value = index;
                list.push(temp);
            })
        }

        //没有头部的ajax
        ,ajaxNoHeader : function (params, callback) {
            var that = this;

            $showMask();
            api.ajax({
                url: params.url,
                method: 'post',
                data: {
                    values : params.data
                }
            }, function(ret, err) {
                if (ret) {
                    if (ret.code === 10001) {
                        api.openWin({
                            name : 'login',
                            url : 'login.html',
                            slidBackEnabled : false
                        });
                        return false;
                    }
                    $hideMask();
                    typeof(callback) === 'function' && callback.apply(this, [ret]);
                } else {
                    $hideMask();
                    typeof(callback) === 'function' && callback.apply(this, [err]);
                }
            });
        }
    };

    window.login = login;
})(window);